package com.cm.Controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
public class ImageUploadController {

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            // 生成新的文件名
            String fileName = generateFileName(file.getOriginalFilename());
            // 设置返回URL的前缀
            String returnUrl = "http://" +request.getServerName() + ":" + request.getServerPort();
            // 文件保存的目录
            String uploadDir = "/path/to/upload/directory";
            Path filePath = Paths.get(uploadDir, fileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 返回URL
            String imageUrl = returnUrl + "/" + fileName;
            return ResponseEntity.ok(imageUrl);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("Error uploading the file");
        }
    }

    private String generateFileName(String originalFilename) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Random r = new Random();
        String randomStr = Integer.toString(r.nextInt(10000));
        return sdf.format(new Date()) + randomStr + "_" + originalFilename;
    }
}
